#!/usr/bin/php
<?php
/*
TODOs
- check if exec() successfully executes gammu after all
- doesn't take into consideraton split/part messages
- for some reason a few numbers are still not captured
*/
 
 /*
Defaul db access:
username: gammu-n5000
passwd: g@mmu-n500O
*/

#Connect to db
#Connect to database
$dbhost = 'localhost';
$dbuser = 'gammu-n5000';
$dbpasswd = 'g@mmu-n500O';
$dbname = 'gammu_n5000';

$conn = mysql_connect($dbhost, $dbuser, $dbpasswd) or die ( mysql_error() );
mysql_select_db($dbname) or die(mysql_error());

######### Start of While(1)
while (1)
{
	#execute gammu command and not have output at STDOUT
	$gammu = exec( "gammu getallsms ", $output1, $retval);

	#write to log file
	logging($retval);

	#count the number of array elements from the gammu output, index starts at 0
	$out_arr_len = count($output1);

	# filenames
	$rdump_file_name = "raw_dump";
	$dump_file_name = "inbox_dump";
	$time_fn = "last_text_date";

	if($out_arr_len != 1) {
		# open a file containing all sms messages
		# open a file containing only inbox messages
		$rdump_file_handle = fopen($rdump_file_name, 'w') or die("can't open or create rawdump file");
		$dump_file_handle = fopen($dump_file_name, 'w') or die("can't open or create dump file");

		# extract all getallsms and save them to the dump_files
		$check_inbox = FALSE;
		foreach($output1 as $value ) {
			if( strcmp( $value,"Location 0, folder \"Inbox\", phone memory") == 0 )
				{$check_inbox = TRUE;}
			if( $check_inbox == TRUE)
				{fprintf($dump_file_handle, "%s \n",$value );}
			fprintf($rdump_file_handle,"%s \n",$value );
		}
		fclose($dump_file_handle) or die("Didnt close dumpfile!\n");
		fclose($rdump_file_handle) or die("Didnt close rawdump!\n");

		# find where the first line of the inbox is compared to the rest of the sms
		exec("grep -n Inbox " . $rdump_file_name . " | cut -f 1 -d :", $inbox_start_line);
		$inbox_start_line = intval($inbox_start_line[0]);
		$inbox_start_index = intval($inbox_start_line) - 1;   # array index where inbox starts
		echo "Inbox start line = $inbox_start_line\n";
		echo "Inbox start index = $inbox_start_index\n";

		#read the date of the last SMS
		if ($last_fh = fopen( $time_fn, 'r')) {
			$last_text_date=fread($last_fh, filesize($time_fn));
			fclose($last_fh) or die("Didnt close timefh (read)!\n");
			echo "last text date = $last_text_date\n";

			# find the line corresponding to the last date of the last SMS
			
			exec ("grep -n \"" . $last_text_date . "\" $dump_file_name|cut -f 1 -d :", $index_of_last_date);
			if (strcmp($index_of_last_date[0],"") == 0) {
				echo "Couldnt find $last_text_date in list of sms, assuming all texts are new.\n";
				exec ("cat " . $dump_file_name . "|wc -l", $index_of_last_date);
				$index_of_last_date = intval($index_of_last_date[0]) - 1;
				$inbox_new_offset = 0;
				echo "Index of last date: $index_of_last_date\n";
				echo "Inbox new offset: $inbox_new_offset\n";
			} else {
				$index_of_last_date = intval($index_of_last_date[0]);
				$inbox_new_offset = $index_of_last_date - 5;
				echo "Index of last date: $index_of_last_date\n";
				echo "Index of new offset: $index_new_offset\n";
			}
		} else {
			# couldn't open file, assume all texts are new
			exec ("cat " . $dump_file_name . "|wc -l", $index_of_last_date);
			echo "Couldnt open last_text_date, assuming all texts are new.\n";
			$index_of_last_date = intval($index_of_last_date[0]) - 1;
			$inbox_new_offset = 0;
			echo "Index of last date: $index_of_last_date\n";
			echo "Inbox new offset: $inbox_new_offset\n";
		}

		$last_text_index = intval($inbox_new_offset) + intval($inbox_start_index);
		echo "Index of last text = $last_text_index\n";     # array index where of last inbox text

		#new SMS messages are from inbox_start_index till last_text_index
		for( $x = $inbox_start_index; $x <= $last_text_index; $x++) {
			if( inbox_msg($output1[$x] ) == FALSE)
				continue;
			$new_sms_msg = $output1[$x + 9];
			$new_sms_num = extract_numbers( $output1[$x + 6] );
			echo "New message is ".$new_sms_msg."\n";
			echo "New number is ".$new_sms_num."\n";
			$new_sms_msg =  mysql_real_escape_string( $new_sms_msg) ;
			#insert data into db
			if( $new_sms_num == NULL)
				continue;
			$query = "insert into `Inbox` values('','Inbox',now(),$new_sms_num, '$new_sms_msg')";
			echo "\n".$query."\n";
			mysql_query($query) or die (mysql_error() );
			$new_sms_msg = $new_sms_num = NULL;
		}

		echo "--- new texts only ---\n";
		system("head -n $inbox_new_offset $dump_file_name");
		echo "--- new texts only ---\n";

		# store the date of the latest text NOW to a file
		unset($last_text_date);
		exec("grep Sent " . $dump_file_name,$latest_text_date);
		exec("rm " . $time_fn);
		$time_fh = fopen($time_fn, 'w') or die ("can't open or create a time date file");
		fprintf( $time_fh, "%s\n",$latest_text_date[0]);
		fclose($time_fh) or die("Didnt close timefh(write)!\n");

		#get the total number of sms messages (includes inbox, outbox etc)
		$sms_msg_num = extract_numbers( $output1[$out_arr_len - 1] );

		#the Location part of each SMS starts at 10, then every other multiple/modulo = 0 of 11! Fantastic :)
		print_r($output1) ; echo "\n array length is ". count($output1)." \n";

		$inbox_msg_count = 1;
		#/*
		#iterate through the gammu out array
		/*foreach ( $output1 as $key => $value ) 
		{
			#echo "key: ".$key." value: ".$value."\n";
			if ( ($key % 11) == 0 ||  (inbox_msg($value) ) == TRUE  )
			{	#get the mobile number, accounting for changes in array index variation/placement
				$mob_number = extract_numbers(  $output1[ $key + 6 ]  ) === "" ? extract_numbers(  $output1[ $key + 5] ) : extract_numbers( $output1[ $key + 6 ]  );
				#settype($mob_number, "integer");
				if ($mob_number == "")
					#$mob_number = 0;
					continue;
				# get_cellnumber(&$output1,$key);
			
				$sent_date =  $output1[ $key + 3 ] ;	
				$message = $output1[$key + 8]." ".$output1[$key +9]." ".$output[$key+10];
				#/*
				echo "||\nMessage is in Inbox: ".$value."\n";
				echo "Message is: ".$message."\n";
				echo "Sender is: ".$mob_number. " \n"; #
				echo "Send date is: ".$sent_date."\n";
				$inbox_msg_count = $inbox_msg_count + 1;
				$esc_msg = addslashes( mysql_real_escape_string( $message) );

				#insert data into db
				$query = "insert into `Inbox` values('','Inbox',now(),$mob_number, '$esc_msg')";
				#echo "\n".$query."\n";
				#mysql_query($query) or die (mysql_error() );
			}

		}*/
		#*/
		echo "\nTotal messages in Inbox is ".$inbox_msg_count."\n";
	}//end If array length != 1

	#empty the array for the next iteration
	#$output2 = $output1;
	unset($output1);
	sleep(5); #sleep for N seconds
	echo "\n\n";
}
######## End of While(1)

/*
########>
FUNCTIONS
########>
*/
#Print output to a logfile

#check if message is in inbox
function inbox_msg($msg)
{
#$test = $output1[288];
if( strcmp( $msg,"Location 0, folder \"Inbox\", phone memory") == 0 )
#	echo "SMS message is in Inbox: ".$test." with return value ".$retval." total SMS messages received ".$sms_msg_num;
	return TRUE;
else
#	echo "SMS message is not in Inbox: ".$test." with return value ".$retval." total SMS messages received ".$sms_msg_num;
	return FALSE;
#	echo "\n SMS array has ".count($output1)." elements \n";
}

function logging($retval)
{
	$log_file_name = "gammu-n500.log";
	$log_file_handle = fopen($log_file_name, 'a') or die("can't open or create log file");

	if($retval == 0)
		$log_out = date('l jS \of F Y h:i:s A'). " - Gammu exited with  ".$retval." - Success \n\n";
	else
		$log_out = date('l jS \of F Y h:i:s A'). " - Gammu exited with  ".$retval." - Error \n\n";

	fwrite($log_file_handle, $log_out);
	fclose($log_file_handle);
}


function extract_numbers($string)
{
	preg_match_all('/([\d]+)/', $string, $match);
	return $match[0][0];
}

#Not working
function get_cellnumber($arr, $key)
{
	if (extract_numbers( $arr[ $key + 6 ] ) === "")
		$mob_number = extract_numbers( $arr[ $key + 5] );
		if ( extract_numbers( $arr[ $key + 5] ) ===""  )
			$mob_number = 0;
	else if (extract_numbers( $arr[ $key + 5] ) === ""  )
                $mob_number = extract_numbers( $arr[ $key + 6] );
                if ( extract_numbers( $arr[ $key + 6] ) ===""  )
                        $mob_number = 0;
	return $mob_number;
	#$mob_number = extract_numbers( $arr[ $key + 6 ] ) === "" ? extract_numbers( $arr[ $key + 5] ) : extract_numbers( $arr[ $key + 6 ] );
}

/*
return BOOLEAN if new message arrives. Compare db sms_count value to current sms_count value
*/
function new_msg()
{
}

?>
